package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private  Map<String, Map<String,HttpServlet>> appServletMap;

    public RequestProcessor(Socket socket, Map<String, Map<String,HttpServlet>> appServletMap) {
        this.socket = socket;
        this.appServletMap = appServletMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            //http://localhost:8080
            // /demo/query?userName=lilei
            String requestURL=request.getUrl();
            //String demoUrl=requestURL.split("8080/")[1];
            String[]demoReqs=requestURL.split("/");
            String demoName=demoReqs[1];
            //暂时不考虑待参数的方法
            String servletURL="/"+demoReqs[2];
            if(appServletMap.get(demoName) == null) {
                System.out.println("应用不存在！！");
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                Map<String,HttpServlet> servletMap=appServletMap.get(demoName);
                HttpServlet httpServlet =servletMap.get(servletURL) ;
                if (httpServlet==null){
                    response.outputHtml(request.getUrl());
                }else{
                    httpServlet.service(request,response);
                }
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
